package zing.downloader.executor;

import zing.downloader.entity.Song;
import zing.downloader.interfaces.IDownloadExecutor;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DownloadExecutor implements IDownloadExecutor {

    private final int MAX_DOWNLOAD = 2;

    private ExecutorService pool = Executors.newFixedThreadPool(MAX_DOWNLOAD);

    @Override
    public void downloadListOfSong(List<Song> songs) {
        for (Song song : songs) {
            pool.submit(new DownloadTask(song));
        }
        awaitTermination();
    }

    private void awaitTermination() {
        try {
            pool.shutdown();
            pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
